<template>
  <!-- 附件上传控件 -->
  <div>
    <div class="form-components" v-if="!$attrs.onlyShow">
      <div v-if="readonly" class="form-readonly"></div>
      <el-upload
        class="upload-demo"
        action="#"
        :download="download"
        :multiple="multiple"
        :name="name"
        :accept="acceptStr"
        :limit="limit"
        :file-list="fileList"
        :http-request="uploadFile"
        :before-upload="beforeUpload"
        :show-file-list="false"
        :style="newStyle"
      >
        <el-button size="small" type="primary" :disabled="disabled" :loading="loading">点击上传</el-button>
        <div
          v-if="__config__.showTip"
          slot="tip"
          class="Fg-upload-tips"
          :style="newStyle.font"
        >*{{ tips }}</div>
      </el-upload>
    </div>
    <FilesShow
      v-if="fileList.length"
      :value.sync="fileList"
      :onlyShow="$attrs.onlyShow"
      :readonly="readonly || disabled"
      :dName="dName"
      :download="download"
      @change="handleChange"
    />
  </div>
</template>
<script>
import FilesShow from "../components/filesShow";
import { requestPost2 } from "@/api/data";
import { comMixin } from "../../../utils/comMixins";
export default {
  mixins: [comMixin],
  name: "form-upload",
  model: {
    prop: "value", // 绑定的值，通过父组件传递
    event: "update",
  },
  components: {
    FilesShow,
  },
  props: {
    // 绑定的输入值
    modelValue: {
      type: [String, Number],
      default: "",
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 表单属性
    __config__: {
      type: Object,
      default: () => {},
    },
    // 文件类型
    accept: {
      type: [String, Array],
      default: "",
    },
    // 文件上传地址
    action: {
      type: String,
      default: "",
    },
    // 文件下载地址
    download: {
      type: String,
      default: "",
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 	上传的文件字段名
    name: {
      type: String,
      default: "",
    },
    // 	下载的文件字段名
    dName: {
      type: String,
      default: "",
    },
    // 最大允许上传个数
    limit: {
      type: Number,
      default: 10,
    },
  },
  computed: {
    tips() {
      // 最大上传文件+单位
      const sizeUnit = this.__config__.fileSize + this.__config__.sizeUnit;
      if (this.accept) {
        return `只能上传${this.accept}文件，且不超过${sizeUnit}的文件${
          this.$attrs.remark || ""
        }`;
      }
      return `只能上传不超过${sizeUnit}的文件${this.$attrs.remark || ""}`;
    },
    acceptStr() {
      if (!this.accept) return "";
      return this.accept?.join(",");
    },
  },
  data() {
    return {
      fileList: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
        // {
        //   name: "food2.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
      loading: false,
    };
  },
  watch: {
    modelValue: {
      immediate: true,
      deep: true,
      handler: function (nd, od) {
        try {
          // 回显
          this.fileList = JSON.parse(nd) || [];
        } catch (error) {
          console.log("error", error);
        }
      },
    },
  },
  methods: {
    beforeUpload(file) {
      if (this.fileList.length >= this.limit) {
        this.$message({
          message: `最多允许上传${this.limit}个文件`,
          type: "info",
        });
        return false;
      }
      const fileSize = this.__config__.fileSize; // 文件大小
      const fileUnit = this.__config__.sizeUnit; // 文件单位
      // 实际上传的文件大小单位为B，需要将文件大小限制的单位转换为B
      const maxSize =
        fileSize *
        { KB: 1024, MB: Math.pow(1024, 2), GB: Math.pow(1024, 3) }[fileUnit];
      let isLt = file.size < maxSize; // 判断是否超过文件大小
      if (!isLt) {
        this.$message({
          message: `请上传小于${fileSize + fileUnit}的文件!`,
          type: "info",
        });
        return false;
      } else {
        this.loading = true;
        return true;
      }
    },

    // 自定义文件上传
    uploadFile(file) {
      let formData = new FormData();
      if (Array.isArray(file)) {
        // 选择多个文件
        file.forEach((item) => {
          formData.append(this.name, item.file);
        });
      } else {
        // 选择单个文件
        formData.append(this.name, file.file);
      }
      this.loading = true;
      requestPost2(this.action, formData)
        .then((res) => {
          // 只能上传一个文件，将原文件清空再添加
          if (!this.multiple) {
            this.fileList = [];
          }
          this.onSuccess(res);
        })
        .catch((err) => {
          this.onError(err);
        });
    },
    // 上传成功
    onSuccess(res) {
      if (res.code == 1) {
        try {
          res.result['mfilePath' || "mFilePath"].forEach((path, index) => {
            this.fileList.push({
              id: res.result.idList? res.result.idList[index]: index,
              name: res.result["mfileName" || "mFileName"][index],
              url: window.location.origin + path,
            });
          });
          this.handleChange(this.fileList);
          this.$message({
            message: `上传成功！`,
            type: "success",
          });
          this.loading = false;
        } catch (error) {
          console.log(error);
          this.onError(error);
        }
      } else {
        this.onError(res);
      }
    },
    // 上传失败
    onError(err) {
      this.$message({
        message: err.msg || `上传失败！`,
        type: "error",
      });
      this.loading = false;
    },

    handleChange(fileArr) {
      let value = fileArr.length ? JSON.stringify(fileArr) : null;
      this.$emit("update:modelValue", value);
      this.$emit("change", value);
      this.onChange(value);
    },
  },
};
</script>
